package com.jiang.daily.Q1552;

import java.util.Arrays;

/**
 * @author Jiang
 * @version 1.0
 * @date 2025/02/14 1:15
 */
class Solution {
    public int maxDistance(int[] position, int m) {
        Arrays.sort(position);
        int l = 1, r = position[position.length - 1] - position[0];
        int res = 0;
        while (l <= r) {
            int mid = l + (r - l) / 2;
            if (check(mid, position, m)) {
                res = mid;
                l = mid + 1;
            } else {
                r = mid - 1;
            }
        }
        return res;
    }

    private boolean check(int cur, int[] position, int m) {
        int pre = position[0], cnt = 1;
        for (int i = 1; i < position.length; i++) {
            if (position[i] - pre >= cur) {
                cnt++;
                pre = position[i];
            }
        }
        return cnt >= m;
    }
}
